package tv.youxing.android.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;
import com.othershe.baseadapter.interfaces.OnLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import tv.youxing.android.Interface.UpRefUpdateListener;
import tv.youxing.android.R;
import tv.youxing.android.adapter.CommonRefreshAdapter;
import tv.youxing.android.adapter.ImageAdapter;
import tv.youxing.android.custom.CustomGridView;
import tv.youxing.android.entity.DianZhanModel;
import tv.youxing.android.entity.DynamicDetailsPingLunModel;
import tv.youxing.android.entity.ImageArrayModel;
import tv.youxing.android.entity.UserInfoModel;
import tv.youxing.android.ui.DynamicDetailsActivity;
import tv.youxing.android.ui.LoginActivity;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.PicassoUtils;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;

/**
 * A simple {@link Fragment} subclass.
 */
public class DynamicDetailsFragment_one extends BaseFragment {


    RecyclerView mRecyclerView;
    private CommonRefreshAdapter mAdapter;

    UserInfoModel allData;
    List<UserInfoModel.ResultBean.DataBean> listDatas = new ArrayList<>();
    int user_id = -1;
    int curPageCount = 0;//当前页数
    boolean isRef = true;//是否加载更多
    private MyItemRecyclerViewAdapter mMyItemRecyclerViewAdapter;

    boolean isOneLoad=true;//判断是否第一次加载 滚动到顶部

    public DynamicDetailsFragment_one(int user_id) {
        // Required empty public constructor
        this.user_id = user_id;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_dynamic_details_fragment_one, container, false);


        //使用listview的话会出现5.0以下上滑不能联动的问题
//        mListView = view.findViewById(R.id.lv);
        mRecyclerView = view.findViewById(R.id.list);

        //初始化adapter
        mAdapter = new CommonRefreshAdapter(getActivity(),getContext(), null, true);

        //初始化EmptyView
        View emptyView = LayoutInflater.from(getContext()).inflate(R.layout.empty_layout, (ViewGroup) mRecyclerView.getParent(), false);
        mAdapter.setEmptyView(emptyView);

        //初始化 开始加载更多的loading View
        mAdapter.setLoadingView(R.layout.load_loading_layout);
        //加载失败，更新footer view提示
        mAdapter.setLoadFailedView(R.layout.load_failed_layout);
        //加载完成，更新footer view提示
        mAdapter.setLoadEndView(R.layout.load_end_layout);

        //设置加载更多触发的事件监听
        mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(boolean isReload) {
                loadData(null);
            }
        });

        //设置item点击事件监听

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(mAdapter);



        //loadData(null);

        return view;
    }


    public void loadData(final UpRefUpdateListener listener) {

        HttpParams params = new HttpParams();
        params.put("user_id", user_id);
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        if (isRef) {
            curPageCount++;
            params.put("page", curPageCount);
        }

        RxVolley.post(StaticClass.UserInfoURL, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {

                allData = GsonUtils.GsonToBean(t, UserInfoModel.class);

                if (allData.getCode() == AppConst.TOKENERROR) {
                    getActivity().startActivity(new Intent(getContext(),LoginActivity.class));
                    return;
                }

                listDatas.clear();
                listDatas.addAll(allData.getResult().getData());
                if (allData.getCode() == 200) {

                    if (listDatas.size() > 0) {
                        mAdapter.setLoadMoreData(listDatas);
                        if (isOneLoad) {
                            mRecyclerView.scrollToPosition(0);

                        }
                    } else {
                        mAdapter.loadEnd();
                    }

                } else {
                    mAdapter.loadFailed();
                }
            }
        });
    }

    private void initView() {
//        mListView.setAdapter(new UserInfoDetailsOneAdapter(getActivity(),getContext(),allData.getResult().getData()));
        mMyItemRecyclerViewAdapter = new MyItemRecyclerViewAdapter();
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mMyItemRecyclerViewAdapter);
    }


    /**
     * 列表数据
     */
    class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.layout_item_dynamic, parent, false);
            return new ViewHolder(view);
        }


        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolders, final int position) {

            ViewHolder viewHolder = (ViewHolder) viewHolders;

            //用户头像
            PicassoUtils.loadImageViewSize(getContext(), null, 60, 60, R.drawable.me_def_avater, viewHolder.ivAvatar);


            //名称
            viewHolder.tvName.setText(allData.getResult().getData().get(position).getPublish_user().getUsername());
            //发布内容
            viewHolder.tvContent.setText(allData.getResult().getData().get(position).getContent());
            List<String> urlList = new ArrayList<>();

            urlList = allData.getResult().getData().get(position).getImages();


            //发布的图片
            List<ImageArrayModel> imgs = new ArrayList<>();
            for (int i = 0; i < allData.getResult().getData().get(position).getImage_array().size(); i++) {
                ImageArrayModel model = new ImageArrayModel();

                model.setImage_url(allData.getResult().getData().get(position).getImage_array().get(i).getImage_url());
                model.setThumbnail(allData.getResult().getData().get(position).getImage_array().get(i).getThumbnail());
                imgs.add(model);
            }
            viewHolder.gridView.setAdapter(new ImageAdapter(getActivity(), getContext(), imgs));
            viewHolder.gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                }
            });

            //时间
            viewHolder.tvTime.setText(allData.getResult().getData().get(position).getUpdated_at());

            //点赞
            viewHolder.ivPraise.setSelected(false);

            //点赞数
            final int[] pinglunCount = {Integer.parseInt(allData.getResult().getData().get(position).getLike_count())};


            final int[] like = {allData.getResult().getData().get(position).getIs_like()};


            if (like[0] == 0) {
                //点赞的点击事件
                final ViewHolder finalViewHolder = viewHolder;
                viewHolder.ivPraise.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //post请求简洁版实现
                        HttpParams params = new HttpParams();
                        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
                        params.put("resource_id", allData.getResult().getData().get(position).getTweet_id());
                        params.put("resource_type", 2);


                        RxVolley.post(StaticClass.DianZan, params, new HttpCallback() {
                            @Override
                            public void onSuccess(String t) {
                                DianZhanModel dianZhanModel = GsonUtils.GsonToBean(t, DianZhanModel.class);


                                if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                                    getActivity().startActivity(new Intent(getContext(),LoginActivity.class));
                                    return;
                                }

                                if (dianZhanModel.getCode() == 200) {
                                    if (dianZhanModel.getResult().getIs_like() == 1) {
                                        finalViewHolder.ivPraise.setSelected(true);
//                                int count = pinglunCount + 1;
                                        pinglunCount[0]++;
                                        finalViewHolder.tvPraise.setText(pinglunCount[0] + "");
                                        finalViewHolder.ivPraise.setEnabled(false);
                                        like[0] = 1;
                                    } else {
                                        finalViewHolder.ivPraise.setSelected(false);
                                        finalViewHolder.tvPraise.setText( pinglunCount[0] + "");
                                        like[0] = 0;
                                    }
                                } else {
                                    finalViewHolder.ivPraise.setSelected(false);
                                    finalViewHolder.ivPraise.setEnabled(true);
                                    like[0] = 0;
                                }
                            }
                        });
                    }
                });
            } else {
                viewHolder.ivPraise.setSelected(true);
            }


            //点赞数
            viewHolder.tvPraise.setText(allData.getResult().getData().get(position).getLike_count());

            //说说评论数
            viewHolder.tvComment.setText(allData.getResult().getData().get(position).getComment_count());

            //评论界面
            viewHolder.llPinglun.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getContext(), DynamicDetailsActivity.class);

                    Bundle bundle = new Bundle();


                    DynamicDetailsPingLunModel model = new DynamicDetailsPingLunModel();
                    DynamicDetailsPingLunModel.PublishUserBean model_user = new DynamicDetailsPingLunModel.PublishUserBean();

                    model.setContent(allData.getResult().getData().get(position).getContent());
                    model.setPublish_time(allData.getResult().getData().get(position).getPublish_time());
                    model.setIs_like(like[0]);
                    model.setTweet_id(allData.getResult().getData().get(position).getTweet_id());


                    model.setComment_count(allData.getResult().getData().get(position).getComment_count()+"");
                    model.setLike_count(pinglunCount[0]+"");
                    model_user.setAvatar(allData.getResult().getData().get(position).getPublish_user().getAvatar());
                    model_user.setUsername(allData.getResult().getData().get(position).getPublish_user().getUsername());
                    model.setPublish_user(model_user);
                    bundle.putSerializable("data", model);


                    intent.putExtras(bundle);
                    getContext().startActivity(intent);
                }
            });


            if (allData.getResult().getData().get(position).getPublish_user().getIs_authenticated() == 1) {
                viewHolder.ivVip.setVisibility(View.VISIBLE);
            } else {
                viewHolder.ivVip.setVisibility(View.GONE);
            }
        }

        @Override
        public int getItemCount() {
            return allData != null && allData.getResult().getData().size() > 0 ? allData.getResult().getData().size() : 0;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {


            public final View mView;
            private CircleImageView ivAvatar;
            private TextView tvName;
            private TextView tvContent;
            private CustomGridView gridView;
            private TextView tvTime;
            private ImageView ivPraise;
            private TextView tvPraise;
            private TextView tvComment;
            private RelativeLayout llPinglun;
            private ImageView ivVip;

            public ViewHolder(View view) {
                super(view);
                mView = view;

                ivAvatar = mView.findViewById(R.id.ivIcon);
                tvName = mView.findViewById(R.id.tvName);
                tvContent = mView.findViewById(R.id.tvContent);
                gridView = mView.findViewById(R.id.picGridView);
                tvTime = mView.findViewById(R.id.tvTime);
                ivPraise = mView.findViewById(R.id.ivPraise);
                tvPraise = mView.findViewById(R.id.tvPraise);
                tvComment = mView.findViewById(R.id.tvComment);
                llPinglun = mView.findViewById(R.id.pinglun);
                ivVip = mView.findViewById(R.id.icon_vip);

            }
        }
    }
}